import csv
import os
from datetime import datetime
from schedule import Schedule
from genetic import GeneticOptimize

# 课程ID到中文名称映射
COURSE_MAP = {
    201: "高等数学",
    202: "大学英语",
    203: "人工智能导论",
    204: "大学物理",
    205: "数据结构",
    206: "计算机网络"
}

# 教师ID到中文姓名映射 
TEACHER_MAP = {
    11101: "张教授",
    11102: "李教授",
    11103: "王教授",
    11104: "赵教授",
    11105: "刘教授",
    11106: "陈教授"
}

# 班级ID到中文名称映射
CLASS_MAP = {
    1201: "计算机",
    1202: "软件工程",
    1203: "人工智能"
}

def export_to_csv(schedule, filename):
    """导出课程表到CSV文件"""
    # 创建时间表矩阵
    timetable = [['' for _ in range(6)] for _ in range(6)]
    
    # 设置表头
    timetable[0] = ['节次/星期', '星期一', '星期二', '星期三', '星期四', '星期五']
    
    # 初始化
    for slot in range(1, 6):  # 第1-5节课
        timetable[slot][0] = f'第{slot}节'
    for s in schedule:
        day_index = s.weekDay  # 1-5 对应周一至周五
        slot_index = s.slot    # 1-5 对应第1-5节课
        
        if 1 <= day_index <= 5 and 1 <= slot_index <= 5:
            # 使用中文映射
            course_name = COURSE_MAP.get(s.courseId, f"未知课程({s.courseId})")
            teacher_name = TEACHER_MAP.get(s.teacherId, f"未知教师({s.teacherId})")
            
            timetable[slot_index][day_index] = f"{course_name}（{teacher_name}）"
    
    # 写入CSV
    with open(filename, 'w', newline='', encoding='utf-8-sig') as f:
        writer = csv.writer(f)
        writer.writerows(timetable)

if __name__ == '__main__':
    schedules = []

    schedules.append(Schedule(201, 1201, 11101))  
    schedules.append(Schedule(201, 1201, 11101))
    schedules.append(Schedule(202, 1201, 11102))  
    schedules.append(Schedule(202, 1201, 11102))
    schedules.append(Schedule(203, 1201, 11103))  
    schedules.append(Schedule(203, 1201, 11103))
    schedules.append(Schedule(206, 1201, 11106)) 
    schedules.append(Schedule(206, 1201, 11106))

    schedules.append(Schedule(202, 1202, 11102)) 
    schedules.append(Schedule(202, 1202, 11102))
    schedules.append(Schedule(204, 1202, 11104))  
    schedules.append(Schedule(204, 1202, 11104))
    schedules.append(Schedule(206, 1202, 11106)) 
    schedules.append(Schedule(206, 1202, 11106))

    schedules.append(Schedule(203, 1203, 11103)) 
    schedules.append(Schedule(203, 1203, 11103))
    schedules.append(Schedule(204, 1203, 11104))  
    schedules.append(Schedule(204, 1203, 11104))
    schedules.append(Schedule(205, 1203, 11105))  
    schedules.append(Schedule(205, 1203, 11105))
    schedules.append(Schedule(206, 1203, 11106)) 
    schedules.append(Schedule(206, 1203, 11106))

    ga = GeneticOptimize(popsize=50, elite=10, maxiter=500)
    all_schedules = ga.evolution(schedules, 3)

    # 创建输出目录
    output_dir = "课程表输出"
    os.makedirs(output_dir, exist_ok=True)
    
    # 获取所有班级ID
    class_ids = set(s.classId for s in all_schedules)
    
    print(f"导出中文课程表...")
    
    # 为每个班级生成课程表
    for class_id in class_ids:
        class_schedules = [s for s in all_schedules if s.classId == class_id]
        
        if class_schedules:
            class_name = CLASS_MAP.get(class_id, f"未知班级({class_id})")
            
            # 导出CSV格式
            csv_filename = os.path.join(output_dir, f"{class_name}_课程表.csv")
            export_to_csv(class_schedules, csv_filename)
            
            print(f"班级 {class_name} 的课程表已导出: {csv_filename}")
    
    print("导出完成！")
    
    # 生成课程映射说明文件
    mapping_filename = os.path.join(output_dir, "课程映射说明.csv")
    with open(mapping_filename, 'w', encoding='utf-8-sig') as f:
        writer = csv.writer(f)
        writer.writerow(["课程ID", "课程名称", "教师ID", "教师名称"])
        for course_id, course_name in COURSE_MAP.items():
            # 查找该课程的教师
            teacher_id = next((s.teacherId for s in schedules if s.courseId == course_id), "未知")
            teacher_name = TEACHER_MAP.get(teacher_id, f"未知教师({teacher_id})")
            writer.writerow([course_id, course_name, teacher_id, teacher_name])
    
    print(f"课程映射说明已导出: {mapping_filename}")